<template>
  <div class="app-container treeselect-main" v-loading="loading">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="所属仓库" prop="depotId">
        <el-select
          v-model="queryParams.depotId"
          placeholder="请选择仓库"
          clearable
          size="small"
        >
          <el-option
            v-for="depot in depotOptions"
            :key="depot.id"
            :label="depot.name"
            :value="depot.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资编码" prop="code">
        <el-input
          v-model="queryParams.pCode"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['equipment:goods:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportQr"
          v-hasPermi="['equipment:goods:exportQr']"
          >二维码下载</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleDownload"
          >选中二维码下载</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="allRefreshQr"
          v-hasPermi="['equipment:goods:allRefreshQr']"
          >刷新二维码</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="goodsList"
      @selection-change="handleSelectionChange"
      max-height="550"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column
        label="名称"
        align="center"
        prop="name"
        minWidth="140px"
      />
      <!--      <el-table-column label="类型" align="center" prop="type" />-->
      <el-table-column label="所属仓库" align="center" prop="depotName" />
      <el-table-column
        label="物资编码"
        align="center"
        prop="basicProductInfo.code"
      />
      <el-table-column
        label="存放物资"
        align="center"
        prop="materialIdName"
        minWidth="140px"
      />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="二维码" align="center" prop="qrUrl">
        <template slot-scope="scope">
          <img :src="scope.row.qrUrl" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:goods:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:goods:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="newQrCode(scope.row)"
            v-hasPermi="['equipment:goods:refreshQr']"
            >刷新二维码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货位对话框 -->
    <el-dialog
      v-myFullscreen
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
      v-myDialogDrag
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="所属仓库" prop="depotId">
                <el-select
                  v-model="form.depotId"
                  placeholder="请选择仓库"
                  :disabled="openDisabled"
                  ref="selectDepot"
                  @change="getDepotByParentId"
                >
                  <el-option
                    v-for="depot in depotOptions"
                    :key="depot.id"
                    :label="depot.name"
                    :value="depot.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属库位" prop="goodsSpaceId">
              <treeselect
                :searchable="false"
                v-model="form.goodsSpaceId"
                :options="depotSpaceOptions"
                :multiple="true"
                :show-count="true"
                class="treeselect-main"
                @select="changeCode"
                :normalizer="normalizer"
                placeholder="请选择库位"
                :disabled="openDisabled || form.depotId == null"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放物资" prop="materialIdName">
              <el-input
                v-model="form.materialIdName"
                placeholder="请输入存放物资"
                :disabled="form.materialIdName != null"
                suffix-icon="el-icon-search"
                @click.native="selectInPro"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="编号" prop="code">
                <el-input
                  v-model="form.code"
                  placeholder="请输入编号"
                  :disabled="openDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入名称"
                  :disabled="openDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单价（元）" prop="price">
                <el-input
                  v-model="form.price"
                  placeholder="请输入名称"
                  :disabled="openDisabled"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="类型" prop="type">-->
          <!--              <el-select v-model="form.type" placeholder="请选择类型" :disabled="openDisabled">-->
          <!--                <el-option label="请选择字典生成" value="" />-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                :disabled="openDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二维码地址" prop="qrUrl">
              <!--              <el-input v-model="form.qrUrl" placeholder="请输入二维码地址" :disabled="openDisabled" />-->
              <el-image :src="form.qrUrl"></el-image>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <ProductSelect ref="selectPro" @childFn="parentFn" />
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  listDepotByAncestors,
  newQrCode,
  allRefreshQr,
} from "@/api/equipment/materials/goods";
import { listDepot, getDepot } from "@/api/equipment/materials/depot";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ProductSelect from "./productSelect";
import { downLoadZip, downLoadZip2, resolveBlob2 } from "@/utils/zipdownload";
export default {
  name: "Goods",
  components: {
    Treeselect,
    ProductSelect,
  },
  data() {
    return {
      //弹窗是否禁止编辑
      openDisabled: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货位表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        code: null,
        name: null,
        type: null,
        depotId: null,
        depotSpaceId: null,
        materialId: null,
        qrUrl: null,
        ids: null,
        pCode: null,
      },
      // 库查询参数
      depotParams: {
        type: null,
        parentId: null,
        ancestors: null,
      },
      // 所属仓库
      depotOptions: [],
      depotSpaceOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [{ required: true, message: "不能为空", trigger: "blur" }],
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        depotId: [{ required: true, message: "不能为空", trigger: "blur" }],
        goodsSpaceId: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        materialIdName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDepot();
  },
  // watch: {
  //     // 监听deptId
  //     'form.goodsSpaceId': 'currGoodsSpaceIdChange'
  // },
  methods: {
    /** 转换库位数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    parentFn(row) {
      this.form.materialId = row.id;
      this.form.materialIdName = row.name;
      this.form.name = row.name;
      this.$forceUpdate();
    },
    // currGoodsSpaceIdChange(val){
    //     if(val.length!=0&&val!=null&&this.open){
    //         getDepot(val[0]).then((response) => {
    //             this.form.code = response.data.code;
    //         });
    //     }
    // },
    changeCode(node, instanceId) {
      this.form.code = node.code + "-";
    },
    resetDepot() {
      this.depotParams = {
        type: null,
        parentId: null,
        id: null,
      };
    },
    getDepot() {
      this.loading = true;
      this.resetDepot();
      this.depotParams.type = "01";
      listDepot(this.depotParams).then((response) => {
        this.depotOptions = response.data;
        this.loading = false;
      });
    },
    getDepotByParentId(code) {
      if (code != 0) {
        this.form.goodsSpaceId = null;
      }
      this.loading = true;
      this.depotSpaceOptions = [];
      listDepotByAncestors(this.form.depotId).then((response) => {
        const data = {
          id: this.form.depotId,
          name: this.$refs.selectDepot.selected.label,
          children: [],
        };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.depotSpaceOptions.push(data);
        // console.log(data)
        this.loading = false;
      });
    },
    selectInPro() {
      if (
        (!this.openDisabled && this.form.materialIdName == null) ||
        this.$store.state.user.name == "admin"
      ) {
        this.$refs["form"].validateField(["depotId"], (valid) => {
          if (!valid) {
            this.$refs.selectPro.show(this.form.depotId);
          }
        });
      }
    },
    /** 查询货位列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        type: null,
        depotId: null,
        goodsSpaceId: null,
        depotSpaceId: null,
        materialId: null,
        materialIdName: null,
        qrUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openDisabled = false;
      this.open = true;
      this.title = "添加货位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.openDisabled = false;
      const id = row.id || this.ids;
      getGoods(id).then((response) => {
        this.form = response.data;
        // let num=response.data;
        // this.form.depotId=Number(num);
        this.getDepotByParentId(0);
        this.open = true;
        this.title = "修改货位";
      });
    },
    /** 查看按钮 */
    handleView(row) {
      this.reset();
      this.openDisabled = true;
      const id = row.id || this.ids;
      getGoods(id).then((response) => {
        this.form = response.data;
        this.getDepotByParentId(0);
        this.open = true;
        this.title = "查看货位";
      });
    },
    newQrCode(row) {
      const id = row.id;
      newQrCode(id).then((response) => {
        this.msgSuccess("刷新二维码成功。");
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const rLoading = this.openLoading();
            addGoods(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              })
              .catch((error) => {
                rLoading.close();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除货位编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delGoods(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "equipment/goods/export",
        {
          ...this.queryParams,
        },
        "货位" + this.parseTime(new Date()) + ".xlsx"
      );
    },
    handleDownload(row) {
      const ids = row.id || this.ids;
      /*downloadProductInfo(ids).then(response =>{
                  resolveBlob2(response,'物料二维码');
                });*/
      // this.downLoadZip2("equipment/goods/download", ids, '货位二维码'+this.parseTime(new Date)+'.zip');
      this.queryParams.ids = ids;
      this.download(
        "equipment/goods/downloadByIds",
        {
          ...this.queryParams,
        },
        "货位二维码" + this.parseTime(new Date()) + ".zip"
      );
    },
    handleExportQr() {
      this.download(
        "equipment/goods/download",
        {
          ...this.queryParams,
        },
        "货位二维码" + this.parseTime(new Date()) + ".zip"
      );
    },
    allRefreshQr() {
      this.loading = true;
      allRefreshQr().then((response) => {
        this.msgSuccess("刷新二维码成功。");
        this.getList();
        this.loading = false;
      });
    },
  },
};
</script>
